<?php
/**
 * Utilities.
 * @package safsi
 */

/**
 * Utilities.
 * @package safsi
 */
class safsi_Util {

    static public function TRIM_LEADING($input = null) {
        if ( $input !== null ) {
            $input = preg_replace('|^' . DIRECTORY_SEPARATOR . '+|', '', $input);
        }
        return $input;
    }

    static public function TRIM_TRAILING($input = null) {
        if ( $input !== null ) {
            $input = preg_replace('|' . DIRECTORY_SEPARATOR . '+$|', '', $input);
        }
        return $input;
    }

    static public function TRIM_BOTH($input = null) {
        if ( $input !== null ) {
            $input = self::TRIM_LEADING(self::TRIM_TRAILING($input));
        }
        return $input;
    }

    static public function GENERATE_PATH_FROM_PARTS() {
        $parts = func_get_args();
        return implode(DIRECTORY_SEPARATOR, $parts);
    }

    /**
     * Determine a sane MIME type for a specified filename.
     *
     * Uses finfo to try and determine a MIME type for a specified
     * filename. If no MIME type is located, it will return a sane
     * default (application/octet-stream).
     *
     * Borrowed heavily from:
     * http://us.php.net/manual/en/function.finfo-file.php#82757
     * @param string $filename Filename
     * @returns string MIME type.
     */
    static public function DETERMINE_MIME_TYPE($filename, $default = 'application/octet-stream') {
        $ftype = $default;
        try {
            if ( function_exists('finfo_open') ) {
                // If the finfo functions exist, use those.
                $finfo = finfo_open(FILEINFO_MIME);
                if ($finfo !== FALSE) {
                    $fres = finfo_file($finfo, $filename);
                    if ( ($fres !== FALSE) && is_string($fres) && (strlen($fres)>0) ) {
                        $ftype = $fres;
                    }
                    finfo_close($finfo);
                }
            } else {
                // Default to standard PHP method.
                $ftype = mime_content_type($filename);
            }
        } catch (Exception $e) {
            // noop
        }
        return $ftype;
    }

}
?>
